<?php

if(!defined('PATH')) exit();

class Search extends Controller {

	protected $default_action = 'form';

	public $_title = 'Search';

	public function __construct() {
		parent::__construct();
	}

	public function action_check() {
		if(!isset($this->paramsURI[2]))
		{
			if(isset($_POST['name']) and $_POST['name'])
			{
				$name = ucfirst(Helper_General::clean($_POST['name']));
				if (strlen($name) >= 5 && $this->archez->checkBaseName($name)) { // without check name = insecure, because you can put string like A%%%%
					
					$match = $this->db->query('SELECT `name` FROM `players` WHERE `name` = ' . $this->db->quote($name))->fetch();
					$query = $this->db->query('SELECT `name` FROM `players` WHERE `name` LIKE ' . $this->db->quote('%'.$name.'%'));
					
					if ($match) {
						$this->redirect(PATH . '/search/check/' . urlencode(strtolower($match['name'])));
					} else if ($query) {
						$view = new View('search/possible_check');
						$view->name = $name;
						$view->query = $query;
						$view->render();
					}
				} else {
					$this->archez->showMsg('Keyword must be at least 5 characters long. You can use only a-z and spaces. Max lenght of name is 25 characters, <a href="' . PATH . '/search/form/">click here</a> to go back.', 'error');
				}
			}
			else
			{
				$this->archez->showMsg('You must fill the name field to search, <a href="' . PATH . '/search/form/">click here</a> to go back.', 'error');
			}
		}
		else
		{

			$get = urldecode($this->paramsURI[2]);

			$player = $this->ots->createObject('Player');
			if (is_numeric($get)) {
				$player->load($get);
			} else {
				$player->find($get);
			}
			if($player->isLoaded())
			{
				$view = new View('search/check');
				$view->player = $player;
				$view->render();
			}
			else
			{
				$this->archez->showMsg('Player doesn\'t exist, <a href="' . PATH . '/search/form/">click here</a> to go back.', 'error');
			}
		}
	}

	public function action_form() {
		$view = new View('search/form');
		$view->render();
	}
}
?>